{% extends "base.html" %}
{% load staticfiles %}

{% block title %}合约管理{% endblock %}

{% block styles %}
    <style>
        label {
            width: 100px;
            margin-left: 10%
        }

        input {
            width: 150px
        }

    </style>
{% endblock %}

{% block content %}
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">警告</h4>
                </div>
                <div class="modal-body">默认合约不可修改</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>
    <section class="content-header">
        <h1>
            合约管理
            <small>{{ allHtml.title }}</small>
        </h1>
        <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-dashboard"></i>PY</a></li>
            <li class="active">合约管理</li>
        </ol>
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="row">
            <div class="col-xs-12">
                <div class="nav-tabs-custom">
                    <ul class="nav nav-tabs">
                        <li class="active"><a href="#fa-icons" data-toggle="tab">合约列表</a></li>
                    </ul>

                    <div class="tab-content ">
                        <div class="tab-pane active mailbox-messages" id="fa-icons">
                            <div class=" mailbox-messages">
                                <table id="toolbar"></table>
                                <table class="table table-bordered table-striped table-hover" id="InstrumentTable">

                                </table>
                            </div>
                        </div>
                        <div class="tab-pane" id="glyphicons">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>


    <!-- UserModal content -->
    <div class="modal fade" id="modal_backtest_detail">
        <div class="modal-dialog" style="width: 450px;">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title"></h4>
                </div>
                <div class="modal-body" style="padding: 30px;height:400px">
                    <form id="save_instrument" action="{% url 'Strategy:instrument_modify' %}" method="post">
                        <div style="margin-top:3%"><label>合约代码</label><input class="opts" id="InstrumentID"
                                                                             name="InstrumentID" type="text"
                                                                             placeholder="合约代码"></div>
                        <div style="margin-top:3%"><label>合约名称</label><input class="opts" id="InstrumentName"
                                                                             name="InstrumentName" type="text"
                                                                             placeholder="合约名称"></div>
                        <div style="margin-top:3%"><label>交易所</label>
                            <select class="opts" id="ExchangeID" name="ExchangeID">
                                <option name="ExchangeID" value="3">
                                    上期所
                                </option>
                                <option name="ExchangeID" value="4">
                                    郑商所
                                </option>
                                <option name="ExchangeID" value="6">
                                    外汇交易中心
                                </option>
                                <option name="ExchangeID" value="7">
                                    中金所
                                </option>
                                <option name="ExchangeID" value="9">
                                    大商所
                                </option>
                                <option name="ExchangeID" value="a">
                                    上海黄金交易所
                                </option>
                            </select>
                        </div>
                        <div style="margin-top:3%"><label>保证金率</label><input class="opts" id="MarginRate"
                                                                             name="MarginRate"
                                                                             type="text" placeholder="保证金率"></div>
                        <div style="margin-top:3%"><label>合约乘数</label><input class="opts" id="Volume" name="Volume"
                                                                             type="text" placeholder="合约乘数"></div>
                        <div style="margin-top:3%"><label>最小变动价位</label><input class="opts" id="Price" name="Price"
                                                                               type="text" placeholder="最小变动价位"></div>
                        <div style="margin-top:3%"><label>持仓类型</label>
                            <select class="opts" id="Position" name="Position">
                                <option name="Position" value="2">
                                    综合持仓
                                </option>
                                <option name="Position" value="1">
                                    净持仓
                                </option>
                            </select>
                        </div>
                        <div style="margin-top:3%">
                            <span style="margin-left:10%;cursor:pointer;padding:5px" class="btn-primary"
                                  onclick="sub(gets)">提交</span>
                            <span style="margin-left:60%;cursor:pointer;padding:5px" class="btn-primary"
                                  onclick="$('#modal_backtest_detail').modal('fade')">取消</span>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- UserModal content -->
    <div class="modal fade" id="modal_in">
        <div class="modal-dialog" style="width: 800px;background-color:#eee">
            <div class="modal-content">
                <div class="modal-body" style="padding:30px;height:430px;overflow:auto">
                    <table id="fileTable">
                        <thead>
                        <tr>
                            <td><strong>合约代码</strong></td>
                            <td><strong>合约名称</strong></td>
                            <td><strong>交易所代码</strong></td>
                            <td><strong>保证金率</strong></td>
                            <td><strong>合约乘数</strong></td>
                            <td><strong>最小变动价位</strong></td>
                            <td><strong>持仓类型</strong></td>
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                </div>
                <div align="right"><span onclick="multi_save()"
                                         style="cursor:pointer;margin-right:30px;padding:5px;margin-bottom:30px"
                                         class="btn-success">确定导入</span></div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="modal_delete">
        <div class="modal-dialog" style="width: 300px;background-color:#eee">
            <div class="modal-content">
                <div class="modal-body" style="padding:5px;height:80px;overflow:auto">
                    <div>
                        <p style="margin-top:10px;margin-left:5px;">是否确定删除合约</p>
                        <div>
                            <span id="del" sid="" onclick="quit__()"
                                  style="padding:2px;cursor:pointer;float:right;margin-right:10px" class="btn-success">取消</span>
                            <span onclick="del_()" style="padding:2px;cursor:pointer;float:right;margin-right:10px"
                                  class="btn-success">确定</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block scripts %}


    <script type="text/javascript">
        function gets() {
            data = {
                'InstrumentID': JSON.stringify([$('#InstrumentID').val()]),
                'InstrumentName': JSON.stringify([$('#InstrumentName').val()]),
                'ExchangeID': JSON.stringify([$('#ExchangeID').val()]),
                'MarginRate': JSON.stringify([$('#MarginRate').val()]),
                'Volume': JSON.stringify([$('#Volume').val()]),
                'Price': JSON.stringify([$('#Price').val()]),
                'Position': JSON.stringify([$('#Position').val()]),
                'sum': '1'
            }
            return data;
        }

        function multi_save() {
            var data = {
                InstrumentID: [],
                InstrumentName: [],
                ExchangeID: [],
                MarginRate: [],
                Volume: [],
                Price: [],
                Position: []
            }
            $("td[type='Symbol']").each(function (i, e) {
                data['InstrumentID'][i] = $(e).text()
            });
            $("td[type='SymbolName']").each(function (i, e) {
                data['InstrumentName'][i] = $(e).text()
            });
            $("td[type='ExchID']").each(function (i, e) {
                data['ExchangeID'][i] = $(e).text()
            });
            $("td[type='MarginRatio']").each(function (i, e) {
                data['MarginRate'][i] = $(e).text()
            });
            $("td[type='Multiple']").each(function (i, e) {
                data['Volume'][i] = $(e).text()
            });
            $("td[type='PriceTick']").each(function (i, e) {
                data['Price'][i] = $(e).text()
            });
            $("td[type='PositionType']").each(function (i, e) {
                data['Position'][i] = $(e).text().replace(/\n/g, '')
            });
            data['sum'] = data['InstrumentID'].length;
            for (var i in data) {
                data[i] = JSON.stringify(data[i]);
            }

            function f() {
                return data;
            }

            sub(f);
        }

        function sub(func) {
            data = func();
            if (data['InstrumentID'] == '[""]' || data['InstrumentName'] == '[""]') {
                return;
            }
            $.post("{% url 'Strategy:instrument_modify' %}", data, function (r) {
                window.location.reload();
            });
        }

        function modify(id) {
            $('.modal-title').text('修改');
            $.get("{% url 'Strategy:instrument_modify' %}", {'instrumentid': id}, function (r) {
                if (r) {
                    for (var key in r) {
                        if ($('#' + key)) {
                            $('#' + key).val(r[key]);
                        }
                    }
                }
            });
        };

        function create() {
            $('.modal-title').text('新建');
            $('.opts').val("");
        };

        function quit__() {
            $('#modal_delete').modal('hide');
        }

        function _delete(d) {
            $('#modal_delete').modal('show');
            $('#del').attr('sid', d);
        }

        function del_() {
            d = $('#del').attr('sid');//该值是从js动态渲染删除里面拿到的，先_delete，再del_
            $.post("{% url 'Strategy:instrument_modify' %}", {'id': d, 'delete': 1}, function (r) {
                if (r) {
                    window.location.href = "{% url 'Strategy:instrument' %}";
                } else {
                    $('#myModal').modal('show');
                }
            });//post请求的回调函数，空值show"默认合约不可修改"，y值则删除后跳转。
        };

        function InitBootstrapTable(my_url, my_table_id, my_columns, my_filename) {
            $('#' + my_table_id).bootstrapTable('destroy').bootstrapTable({
                url: my_url,
                method: 'get',
                columns: my_columns,
                toolbar: '#toolbar',
                striped: true,
                cache: false,
                pagination: true,
                sortable: true,
                sortOrder: "asc",
                queryParams: function (pageRequest) {
                    return pageRequest;
                 },
                sidePagination: "server",
                pageNumber: 1,
                pageSize: 10,
                pageList: [10, 25, 50, 100],
                search: true,      //这里的search是bootstrap内置的查询方法，同时可以发给后台做判断  
                strictSearch: false,
                showColumns: true,
                showRefresh: true,
                minimumCountColumns: 2,
                clickToSelect: true,
                uniqueId: "Symbol",
                showToggle: true,
                cardView: false,
                detailView: false,
                showExport: true,
                buttonsAlign: "right",
                exportDataType: "all",
                exportTypes: ['excel'],
                Icons: 'glyphicon-export',
                exportOptions: {
                    fileName: my_filename,
                },
            })
        };
        my_columns = [
            {
                field: 'Symbol',
                title: '合约代码'
            }, {
                field: 'SymbolName',
                title: '合约名称'
            }, {
                field: 'ExchID',
                title: '交易所'
            }, {
                field: 'MarginRatio',
                title: '保证金率'
            }, {
                field: 'Multiple',
                title: '合约乘数'
            }, {
                field: 'PriceTick',
                title: '最小变动价位'
            }, {
                field: 'PositionType',
                title: '持仓类型',
            }, {
                field: 'option',
                title: '操作',
                formatter: function (value, row, index) {
                    return "<span onclick=\"modify('" + value + "')\" class='btn btn-success btn-xs btn-flat btn_operation' data-toggle='modal' data-target='#modal_backtest_detail'> <i class='fa fa-pencil'></i>修改</span> " + "&nbsp<span onclick=\"_delete('" + value + "')\" type='button' class='btn btn-success btn-xs btn-flat btn_operation'> <i class='fa fa-pencil'></i>删除</span> ";
                }
            },
        ];
        InitBootstrapTable("{% url 'Strategy:instrument' %}", "InstrumentTable", my_columns, "symbols");
        $('.fixed-table-toolbar').append("&nbsp <span onclick='create()' type='button' class='btn btn-success btn-xs btn-flat btn_operation' data-toggle='modal' data-target='#modal_backtest_detail'> <i class='fa fa-pencil'></i>新建</span>");
        var import_ = "<a href='javascript:;' onclick='$(\"#InFile\").val(\"\")' class='file'>导入合约文件<input type='file' id='InFile' accept='.csv'></a>";
        $('.fixed-table-toolbar').append($(import_));
        var file1 = document.getElementById('InFile');
        file1.onchange = function () {
            var file = file1.files[0];
            var reader = new FileReader();
            reader.readAsText(file, 'utf-8');
            reader.onload = function () {
                lines = reader.result.split('\n').slice(1);
                $('#modal_in').modal('show');
                var row = [];
                var f = 0;
                var single = false;
                for (var i in lines) {
                    var line = lines[i].replace(/↵/g, '').split(',');
                    if (lines[i].length < 7) {
                        console.log('-');
                        continue;
                    } else if (line.length != 7) {
                        console.log(lines);
                        single = true;
                        break;
                    } else {
                        row[f] = line;
                        f = f + 1;
                    }
                }
                if (!single) {
                    $('#err').remove();
                    var types = ['Symbol', 'SymbolName', 'ExchID', 'MarginRatio', 'Multiple', 'PriceTick', 'PositionType'];
                    $('#fileTable tbody').children().remove();
                    for (var i in row) {
                        var r = "<tr style='background-color:#" + ((i % 2 == 1) ? "fff'>" : "ccc'>");
                        for (var j in row[i]) {
                            r = r + "<td type='" + types[j] + "'>" + row[i][j].replace(/↵/g, '') + "</td>";
                        }
                        r = r + "</tr>";
                        $('#fileTable tbody').append($(r));
                    }
                } else {
                    var r = "<div id='err' align='center'><span>合约文件第" + (row.length + 1) + "行格式错误</span></div>";
                    $('#fileTable').parent().append($(r));
                }
            }
        }
        $('.page-list').css('display', 'none');
        $('.pagination-info').css('display', 'none');
        $('.form-control').attr('placeholder', '合约代码查询');
    </script>
    <style>
        .pagination-info {
            display: none
        }

        .page-list {
            display: none
        }

        #fileTable td {
            width: 120px;
            margin-top: 5px
        }

        .file {
            position: relative;
            display: inline-block;
            background: #D0EEFF;
            border: 1px solid #99D3F5;
            border-radius: 4px;
            padding: 4px 12px;
            overflow: hidden;
            color: #1E88C7;
            text-decoration: none;
            text-indent: 0;
            line-height: 20px;
            float: right;
            margin-top: 12px;
            margin-right: 5px
        }

        .file input {
            position: absolute;
            font-size: 100px;
            right: 0;
            top: 0;
            opacity: 0;
        }

        .file:hover {
            background: #AADFFD;
            border-color: #78C3F3;
            color: #004974;
            text-decoration: none;
        }
    </style>

{% endblock %}